var audioplayUtil = require("../../../utils/audioplay.js")
var timerR = require('../../../utils/bannerTimes.js')
var shareTickets = ""
var interval;
var totalmusic = 100
var audio
var id
var season
var app = getApp()
var isfirst = true;
var timer;
var ispop
var hongbaointerval
var commision_userIds;
var startTime;
var currentTalkAboutId = undefined;
Page({
  data: {
    sharenetimage: getApp().globalData.source + "details/popimg.png",
    adimage: getApp().globalData.source + "advertising/adv.jpg",
    authbg: getApp().globalData.authImg,
    authtitle: getApp().globalData.source + "red_packet/title1.png",
    authbtn2: getApp().globalData.source + "red_packet/btn2.png",
    authdialog: getApp().globalData.source + "dialog/dialog.png",
    jumpalready: false,
    showhongbaoicon: false,
    showhongbao: false,
    hongbaodata: {},
    imgUrls: [
      getApp().globalData.source + 'ttbt_image_icon/d1.png',
      getApp().globalData.source + 'ttbt_image_icon/d2.png',
      getApp().globalData.source + 'ttbt_image_icon/d3.png',
      getApp().globalData.source + 'ttbt_image_icon/d4.png'
    ],
    weburl: "",
    talkabout: "说点什么",
    indicatorDots: true,
    vertical: false,
    iteminfo: {},
    isrefresh: true,
    autoplay: true,
    circular: false,
    interval: 2000,
    duration: "00:00",
    indicatorColor: '#EAEAEA',
    color: '#79C9EC',
    aftermoney: "",
    popupshow: false,
    rangetimers: ['不限时间', '10分钟', '20分钟', '30分钟', '50分钟', '60分钟', '100分钟'],
    timerIndex: ['0', '10', '20', '30', '50', '60', '100'],
    indexNumber: 0, //当前播放音频下标
    timer: '', //播放时间 播放时间统计
    currentPosition: 0, //选定音频的播放位置
    duration: 0, //选定音频的长度
    classfilyDataList: [],
    classfilyCommentDataList: [],
    free: true,
    freetrue: true,
    play: true,
    isweb: true,
    ispop: false,
    collectshow: false,
    list: [],
    history: false,
    buyed: true,
    collected: false,
    animationData: {},
    trans: true,
    time: 0,
    seconds: 0,
    during: '00:00',
    pause: false,
    total: " -- ",
    showsharepop: false,
    totalmusic: 100,
    maxfreelesson: 0,
    maxPage: 10, //每页显示最大行数
    startPoint: 1, //第几页
    totalPages: 1, //总共几页
    page: 1,
    totalCommentPages: 1, //总共几页
    commentPage: 1,
    showbottom: true,
    showloading: true,
    id: '',
    trylisten: false,
    chapterindex: 0,
    nomoney: true, //朱新增
    episodeselectpopshow: false, //朱新增  
    check: true, //朱新增 

    programid: "", //栏目id

    programName: "", //栏目名称
    stopTime: "", //页面停留时长
    userIdss: "", //用户id

    timer: '', //定时器名字
    countDownNum: '2', //倒计时初始值
    dingshihongbaoshow: false,
    dingshihongbao: getApp().globalData.source + "dialog/dingshihongbao.png",
    swiperCurrent: 0,
    showbanner: false,
    indicatorDots: false,
    vertical: false,
    autoplay: true,
    circular: true,
    interval: 5000,
    clickhide: false,
    swiperIndex: 0,
  },


  authbtn: function() {
    var vm = this
    wx.showLoading({
      title: "正在检查网络.."
    })
    this.setData({
      authbtn: true
    })
  },

  //腰部banner的切换事件 
  swiperChange: function(e) {
    console.log(e);
    this.setData({
      swiperCurrent: e.detail.current //获取当前轮播图片的下标
    })
  },

  closePopUp: function() {
    var that = this;
    this.setData({
      dingshihongbaoshow: !that.data.dingshihongbaoshow
    })
  },


  towebdetail: function() {
    var vm = this
    wx.navigateTo({
      url: "/pages/webview/webview?url=" + vm.data.info.groupH5Url,
    })
  },
  bindGetUserInfo: function(e) {
    getApp().authInfo(e);
  },

  confirmbuy: function(seasonsids) {
    var vm = this
    var userIds = wx.getStorageSync("userId") === "" ? -1 : wx.getStorageSync("userId");

    if (this.data.chapterindex == 0) {
      var data = {
        "userId": userIds,
        "programId": id,
        "seasonIds": vm.data.iteminfo.id,
      }
      getApp().requestLoading(getApp().globalData.https + "orderResource/walletRecordEvery",
        "get", data, "正在购买..",
        function(res) {
          console.log("buy" + JSON.stringify(res))
          if (res.code == 0) {
            if (res.data.disPrice < 0) {
              wx.navigateTo({
                url: '../../my/my_wallet/my_wallet',
              })
            } else {
              wx.showToast({
                title: '购买成功',
              })
              vm.setData({
                page: 1
              })
              setTimeout(function() {
                vm.setData({
                  classfilyDataList: []
                })
                vm.getdata(id)
              }, 1000)
            }
          } else if (res.code == "014") {
            wx.showToast({
              title: res.message,
              icon: "none"
            })
            wx.navigateTo({
              url: '../../my/my_wallet/my_wallet',
            })
          } else if (res.code != "0") {
            wx.showToast({
              title: res.message,
              icon: "none"
            })
          }
        },
        function(res) {});
    } else {
      var data = {
        "userId": userIds,
        "programId": id,
        "sort": vm.data.info.sort,
        "currentSeasonId": vm.data.iteminfo.id
      }
      getApp().requestLoading(getApp().globalData.https + "orderResource/buy10Season",
        "get", data, "正在购买..",
        function(res) {
          if (res.code == 0) {
            if (res.data.disPrice < 0) {
              wx.navigateTo({
                url: '../../my/my_wallet/my_wallet',
              })
            } else {
              wx.showToast({
                title: '购买成功',
              })
              vm.setData({
                page: 1
              })
              setTimeout(function() {
                vm.setData({
                  classfilyDataList: []
                })
                vm.getdata(id)
              }, 1000)
            }
          } else if (res.code == "014") {
            wx.showToast({
              title: res.message,
              icon: "none"
            })
            wx.navigateTo({
              url: '../../my/my_wallet/my_wallet',
            })
          } else if (res.code != "0") {
            wx.showToast({
              title: res.message,
              icon: "none"
            })
          }
        },
        function(res) {});
    }

  },
  shiting: function(e) {
    this.tolisten(e)
  },
  chapterclick: function(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      chapterindex: index
    })


  },

  define: function() {
    wx.navigateTo({
      url: '../../bulk_buying/bulk_buying?id=' + id,
    })
  },

  buypopclick: function(index) {
    var that = this
    this.setData({
      iteminfo: that.data.classfilyDataList[index],
      episodeselectpopshow: !that.data.episodeselectpopshow
    })

    var vm = this
    var dataparm;
    dataparm = {
      "programId": id,
      "seasonId": that.data.classfilyDataList[index].id,
      "sort": that.data.info.sort
    }
    app.request(app.globalData.https + "programResource/count10Season",
      "get", dataparm,
      function(res) {
        if (res.code == 0) {
          vm.setData({
            aftermoney: res.data.totalPrice
          })
        }
      });
  },

  //朱新增
  episodeSelectPopShow: function(e) {
    var index = e.currentTarget.dataset.index;
    this.buypopclick(index)
  },
  episodeSelectPopHide: function() {
    var that = this;
    this.setData({
      episodeselectpopshow: !that.data.episodeselectpopshow,
    });
  },


  checkbox: function() {
    var that = this;
    this.setData({
      check: !that.data.check,
    });

    if (!this.data.check) {
      wx.showToast({
        title: '敬请期待',
      })
    }
  },
  //

  //检测该页面是否有红包显示
  checkhongbao: function() {
    var iphone = wx.getStorageSync("iPhone");
    if (iphone != "-1") {
      return
    }
    var vm = this
    var data = {
      "pageConfig": "详情页",
      "userId": wx.getStorageSync("userId")
    }
    getApp().request(getApp().globalData.https + "hd/listen/classify/random",
      "post", data,
      function(res) {
        console.log("红包数据：" + JSON.stringify(res))
        //state=1时,显示红包就开始倒计时，隐藏掉红包入口
        if (res.code == 0) {
          if (res.data.state == 1) {
            var time = 15
            vm.setData({
              showhongbaoicon: true
            })
            if (!vm.data.isweb) {
              hongbaointerval = setInterval(function() {
                if (time <= 0) {
                  clearInterval(hongbaointerval)
                  vm.setData({
                    showhongbaoicon: false
                  })
                }
                time--;
              }, 1000)
              vm.setData({
                hongbaodata: res
              })
            }

          } else {
            vm.setData({
              showhongbaoicon: false
            })
          }
        }
      },
      function(res) {});
  },
  jumptotal: function() {
    wx.navigateTo({
      url: '../../my/mydetail/mydetail',
    })
    this.setData({
      showhongbao: false,
      showhongbaoicon: false
    })
  },
  openhongbao: function() {
    this.setData({
      showhongbao: true
    })
    //领取红包
    var vm = this
    var data = {
      "userId": wx.getStorageSync("userId"),
      "state": 1,
      "tb": vm.data.hongbaodata.tb
    }
    this.setData({
      showhongbaoicon: false
    })
    clearInterval(hongbaointerval)
    getApp().request(getApp().globalData.https + "hd/listen/classify/random/savetb",
      "post", data,
      function(res) {},
      function(res) {});
  },
  closePopUp: function() {
    var that = this;
    that.setData({
      kefushow: false
    })
  },

  //长按支付后的图片弹出保存图片
  viewImage(e) {
    const {
      src
    } = e.target.dataset;
    wx.previewImage({
      urls: [src],
    });
  },

  onkefuEnter: function() {
    var vm = this
    getApp().requestLoading(getApp().globalData.https + "resourcesResource/payWaiterWXPic?type=1",
      "get", '', "获取中..",
      function(res) {
        vm.setData({
          kefubg: getApp().globalData.source + "wxcode/kefu/play_detail_kefu_qrcode.png", //需要调用接口获取二维码TODO....
          kefuerweim: res.data.location,
          kefushow: true, //打开支付成功弹框
        })
      }
    )
  },

  closeredpockets: function() {
    this.setData({
      showhongbao: false
    })
  },


  popUpShow: function() {
    var that = this
    this.setData({
      popupshow: !that.data.popupshow
    })
  },
  popUpHide: function() {
    var that = this
    this.setData({
      popupshow: !that.data.popupshow
    })
  },

  close: function() {
    this.setData({
      collectshow: false
    })
  },
  //  点击时间组件确定事件  
  bindPickerChange: function(e) {
    var vm = this
    var index = e.detail.value;
    var haom = 60 * 1000;
    var timeList = this.data.timerIndex
    var endTime = timeList[index] * haom;
    if (timeList[index] === '0') {
      clearTimeout(timer);
    } else {
      timer = setTimeout(function() {
        //延迟endTime时间后调用停止播放
        audioplayUtil.audio.pause()
        vm.setData({
          pause: false
        })
      }, endTime)
    }
  },
  //全集购买
  pay: function() {
    var vm = this
    this.setData({
      jumpalready: true
    })
    if (commision_userIds != undefined) {
      wx.navigateTo({
        url: '../../my/pay/pay_sure?info=' + JSON.stringify(vm.data.info) + "&commision_userIds=" + commision_userIds,
      })
    } else {
      wx.navigateTo({
        url: '../../my/pay/pay_sure?info=' + JSON.stringify(vm.data.info),
      })
    }

  },

  //拦截判断处理
  interceptAction: function(itemindex) {
    var itemlist = this.data.classfilyDataList
    //判断是否可试听 
    if (this.data.info.category == 0) {
      //免费
    } else {
      //收费节目，未付费做拦截处理
      if (this.data.info.everySeasonBuy != 1) {
        //整集购买
        if (!this.data.info.listen) {
          //还没满足条件   付费/分享
          if (this.data.info.shareStatus == 1) {
            //不可分享，必须付费
            if (itemlist[itemindex].tryStatus == 0) {
              //可试听,不做拦截
            } else {
              //不可试听,需要弹购买窗，拦截处理
              if (this.data.info.everySeasonBuy != 1) {
                //整集购买弹窗
                this.pay()
              } else {
                //分集购买弹窗
                this.buypopclick(itemindex)
              }
              return true
            }
          } else {
            //可分享免费听的
            if (itemlist[itemindex].tryStatus == 0) {
              //可试听,不做拦截
            } else {
              //不可试听,需要弹分享窗,拦截处理
              this.setData({
                collectshow: true
              })
              return true
            }
          }
        }
      } else {
        //分集购买
        if (this.data.info.shareStatus == 1) {
          //不可分享，必须付费
          if (itemlist[itemindex].tryStatus == 0) {
            //可试听,不做拦截
          } else {
            if (itemlist[itemindex].buySelf != 1) {
              //分集购买弹窗
              this.buypopclick(itemindex)
              return true
            }

          }
        } else {
          //可分享免费听的
          if (itemlist[itemindex].tryStatus == 0) {
            //可试听,不做拦截
          } else {
            //不可试听,需要弹分享窗,拦截处理
            this.setData({
              collectshow: true
            })
            return true
          }
        }
      }


    }
  },
  // 选集点击条目事件
  itemclick: function(event) {
    if (this.checklogin()) return
    var itemindex = event.currentTarget.dataset.index;
    if (this.interceptAction(itemindex)) {
      return
    }
    var vm = this;
    //设置选中，并播放当前节目
    this.setData({
      indexNumber: event.currentTarget.dataset.index,
      pause: true,
      play: false,
    })
    var e = null
    wx.setStorageSync("currentPosition" + wx.getStorageSync("programid"), 0)
    audioplayUtil.playaudio(e, vm)

  },


  //下一集
  next: function(e) {
    if (this.checklogin()) return
    if (this.interceptAction(this.data.indexNumber + 1)) {
      return
    }
    var e = null
    var that = this;
    audioplayUtil.next(e, that)
  },

  //上一集
  last: function(e) {
    if (this.checklogin()) return
    if (this.data.indexNumber == 0 || this.data.indexNumber == undefined) {
      if (this.interceptAction(0)) {
        return
      }
    } else {
      if (this.interceptAction(this.data.indexNumber - 1)) {
        return
      }
    }
    if (wx.getStorageSync("userId") == "" || wx.getStorageSync("userId") == undefined) {
      wx.navigateTo({
        url: '../../login/login',
      })
    } else {
      var e = null
      var that = this;
      audioplayUtil.last(e, that)
    }

  },

  /**
   * 获取banner广告
   */
  findProgramBannerAd: function() {
    //加载banner广告数据
    app.request(app.globalData.https + " ",
      "get", "",
      function(res) {
        if (res.code == 0) {
          // 获取系统信息  
          that.setData({
            bannerAd: res.data,
          });
        }
      },
      function(res) {
        console.log(res)
      }
    )
  },

  showDialog: function() {
    this.dialog.showDialog();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.dialog = this.selectComponent("#dialog");
    var vm = this
    this.setData({
      timers: ['不限时间', '10分钟', '20分钟', '30分钟', '50分钟', '60分钟', '100分钟'],
    })

    var comission = options.commission;
    if (comission == "1") {
      commision_userIds = options.userIds;
    }
    if (options.season != undefined) {
      if (options.season == 0) {
        season = 0;
      } else {
        season = options.season - 1;
      }
    } else {
      season = 0
    }

    var channel = options.channel;
    id = options.id;
    // id = "348"
    if (channel != undefined) {
      wx.setStorageSync("channel", channel)
    }
    var showhomeicon = options.showhomeicon == "fx" ? true : ""; //判断是分享页进入还是小程序正常进入 
    if (showhomeicon) {
      this.setData({
        showhomeicon: showhomeicon
      })
    }
    wx.showShareMenu({
      withShareTicket: true
    })
    //网页链接地址
    this.setData({
      programid: id,
      id: id
    })
    ispop = options.pop;
    console.log("ispop" + ispop)
    if (ispop) {
      this.setData({
        collectshow: true,
        ispop: true
      })
    }
    //加载倒计时广告
    var that = this;
    timerR.countDown(that);

    this.getCommentData();
  },
  getalldata: function() {
    this.setData({
      page: 1,
      classfilyDataList: []
    })
    var vm = this
    var data = {
      "startPoint": 1,
      "maxPage": 10,
      "userId": wx.getStorageSync("userId")
    }
    var programid = wx.getStorageSync("programid")
    if (id == programid) {
      vm.setData({
        play: false,
        pause: true,
      })
      vm.getdetails(id, function() {
        audioplayUtil.getProgramCurrentSeason(id, data, vm)
      });
    } else {
      vm.setData({
        play: true,
        pause: false,
      })
      vm.getdetails(id, function() {
        audioplayUtil.getProgramCurrentSeason(id, data, vm)
      });
    }
  },

  tolisten: function(e) {
    var vm = this
    vm.setData({
      pause: !vm.data.pause
    })
    //如果是暂停，关闭记时器 、停止音频
    if (!vm.data.pause) {
      audioplayUtil.stopaudio(e, vm)
      return
    } else {
      vm.setData({
        play: false
      })
      //如果是开始播放 ，开始计时，并播放音乐
      var programid = wx.getStorageSync("programid")
      if (id == programid) {
        audioplayUtil.audio.play()
      } else {
        wx.setStorageSync("currentPosition", 0)
        audioplayUtil.playaudio(e, vm)
      }
    }
  },
  //点击播放按钮
  play: function(e) {
    if (this.checklogin()) return
    this.tolisten(e)
  },

  checklogin: function() {
    if (wx.getStorageSync("userId") == "" || wx.getStorageSync("userId") == undefined) {
      if (wx.getStorageSync("authtype") == "0") {
        this.setData({
          showAuth: true,
          showAuth2: false
        })
      } else {
        this.setData({
          showAuth: false,
          showAuth2: true
        })
      }
      return true
    } else {
      this.setData({
        showAuth: false,
        showAuth2: false
      })
      return false
    }
  },


  // 进度条拖动联动
  slidechange: function(event) {
    var vm = this
    audioplayUtil.bindSliderchange(event, vm)
  },


  // 列表控件点击事件，滑动选择到节目选集
  listclick: function() {
    wx.pageScrollTo({
      scrollTop: 600,
      duration: 200
    })
    this.setData({
      history: false,
      buyed: true,
    })
  },



  //节目介绍
  history: function() {
    this.setData({
      history: true,
      buyed: false,
      collection: false,
      showbottom: false
    })
  },



  //节目介绍
  collection: function() {
    this.setData({
      history: false,
      buyed: false,
      collection: true,
      showbottom: false
    })

  },

  // 收藏
  tocollect: function() {
    if (this.checklogin()) return
    var vm = this
    var dataparm;
    if (!vm.data.collected) {
      this.setData({
        collected: !vm.data.collected
      })
      dataparm = {
        "programId": id,
        "seasonId": 0,
        "status": 2,
        "userId": wx.getStorageSync("userId")
      }
      app.request(app.globalData.https + "programResource/mark",
        "post", dataparm,
        function(res) {
          if (res.code == 0) {
            // getApp().showMsgToast(getApp().globalData.collectSuceessTxt)
            vm.showDialog()
          }
        });
    } else {
      this.setData({
        collected: !vm.data.collected
      })
      dataparm = {
        "programId": id,
        "seasonId": 0,
        "status": 2,
        "userId": wx.getStorageSync("userId")
      }
      app.request(app.globalData.https + "programResource/delHistoryMark",
        "post", dataparm,
        function(res) {});
    }
  },

  // 节目选集
  buyed: function() {
    this.setData({
      history: false,
      buyed: true,
      collection: false,
    })
  },


  //分享列表
  tosharelist: function() {
    wx.navigateTo({
      url: '../sharelist/sharelist',
    })
  },
  /**
   * 获取栏目详情
   */
  getdetails: function(id, success) {
    var vm = this
    var data = {
      "startPoint": vm.data.page,
      "maxPage": vm.data.maxPage,
    }
    var userIds = wx.getStorageSync("userId") === "" ? -1 : wx.getStorageSync("userId");
    getApp().request(getApp().globalData.https + "programResource/programDetail/" + id + "/" + userIds,
      "get", data,
      function(res) {
        vm.setData({
          showloading: false
        })
        if (res.code == 0) {
          vm.checkhongbao()
          wx.setNavigationBarTitle({
            title: res.data.title
          })
          if (res.data.useH5 == 1) {
            vm.setData({
              isweb: false
            })
          } else {
            var date = new Date();
            vm.setData({
              isweb: true,
              weburl: res.data.h5Url + "?openID=" + wx.getStorageSync("userId") + "&t=" + date.getTime(),
            })
          }
          var linkurl = [];
          linkurl.push(res.data.groupH5ImageUrl)
          vm.setData({
            info: res.data,
            showbanner: res.data.groupH5,
            weblinkurl: linkurl,
            indexNumber: res.data.currentSeason - 1,
            collected: (res.data.markStatus == 0)
          })
          success();

          wx.setStorageSync("playimg", res.data.shareImageUrl)
        }
      },
      function(res) {});
  },
  onenter: function(event) {
    console.log(event.detail.value)
    if (this.checklogin()) return
    this.comment();
  },

  talkto: function(event) {
    var vm = this
    var index = event.currentTarget.dataset.index;
    currentTalkAboutId = vm.data.classfilyCommentDataList[index].id
    this.setData({
      talkabout: "回复" + vm.data.classfilyCommentDataList[index].user.wxNickname + ":"
    })

    if (vm.data.classfilyCommentDataList[index].countDiscuss == 0) {
      return
    }
    if (this.data.classfilyCommentDataList[index].commentlist == undefined) {
      this.getBottomCommentData(index)
    } else {
      var list = vm.data.classfilyCommentDataList
      list[index].commentlist = undefined
      vm.setData({
        classfilyCommentDataList: list,
      })
    }
  },

  /**
   *  评论
   */
  comment: function() {
    var vm = this
    if (vm.data.content==''){
      getApp().showMsgToast("请输入评论内容")
      return
    }
    if (currentTalkAboutId == undefined) {
      var data = {
        content: vm.data.content,
        userId: wx.getStorageSync("userId"),
        programId: id
      }
    } else {
      var data = {
        discussId: currentTalkAboutId,
        content: vm.data.content,
        userId: wx.getStorageSync("userId"),
        programId: id
      }
    }

    getApp().requestLoading(getApp().globalData.https + "userResource/discussProgram",
      "post", data, "提交中..",
      function(res) {
        if (res.code == 0) {
          setTimeout(function() {
            getApp().showMsgToast("评论成功")
          }, 1000)
          vm.getCommentData();
          vm.setData({
            commentPage: 1,
            content: "",
            talkabout: "说点什么"
          })
          currentTalkAboutId = undefined
        } else {
          getApp().showMsgToast(res.msg)
        }
      });
  },

  change: function(event) {
    this.setData({
      content: event.detail.value,
    })
  },
  commentdetails: function(event) {
    var vm = this
    var index = event.currentTarget.dataset.index;

    if (vm.data.classfilyCommentDataList[index].countDiscuss == 0) {
      return
    }
    if (this.data.classfilyCommentDataList[index].commentlist == undefined) {
      this.getBottomCommentData(index)
    } else {
      var list = vm.data.classfilyCommentDataList
      list[index].commentlist = undefined
      vm.setData({
        classfilyCommentDataList: list,
      })
    }
  },
  /**
   *  评论列表
   */
  getCommentData: function() {
    var vm = this

    var data = {
      startPoint: vm.data.commentPage,
      maxPage: vm.data.maxPage,
      programId: id
    }
    getApp().requestLoading(getApp().globalData.https + "programResource/program/discuss",
      "get", data, "加载中..",
      function(res) {
        wx.stopPullDownRefresh()
        if (res.code == 0) {
          if (vm.data.commentPage == 1) {
            vm.setData({
              classfilyCommentDataList: res.data.data,
              totalCommentPages: res.data.totalPages,
            })
          } else {
            vm.setData({
              classfilyCommentDataList: vm.data.classfilyCommentDataList.concat(res.data.data),
              totalCommentPages: res.data.totalPages,
            })
          }

        }
      });
  },


  /**
   *  一级评论列表
   */
  getBottomCommentData: function(index) {
    var vm = this
    var data = {
      discussId: vm.data.classfilyCommentDataList[index].id
    }
    getApp().requestLoading(getApp().globalData.https + "programResource/program/discussDiscussLevel1",
      "get", data, "加载中..",
      function(res) {
        wx.stopPullDownRefresh()
        if (res.code == 0) {
          var list = vm.data.classfilyCommentDataList
          list[index].commentlist = res.data
          vm.setData({
            classfilyCommentDataList: list,
          })
        }
      });
  },
  /**
   * 获取单个栏目下所有集数列表
   */
  getdata: function(id) {
    var vm = this
    var rate = vm.data.indexNumber / 10
    rate = Math.floor(rate)
    var data
    if (wx.getStorageSync("userId") == undefined || wx.getStorageSync("userId") == '') {
      data = {
        startPoint: vm.data.page,
        maxPage: 10 * rate + 10,
      }
    } else {
      data = {
        userId: wx.getStorageSync("userId"),
        startPoint: vm.data.page,
        maxPage: 10 * rate + 10,
      }
    }

    getApp().requestLoading(getApp().globalData.https + "/programResource/seasons/" + id,
      "get", data, "加载中..",
      function(res) {
        wx.stopPullDownRefresh()
        if (res.code == 0) {
          vm.setData({
            classfilyDataList: vm.data.classfilyDataList.concat(res.data.data),
            totalPages: res.data.totalPages,
          })
          var e = null
          console.log("走到这里了")
        }
      });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      showloading: true,
    })
    //埋点 开始
    var s = new Date()
    startTime = s;
    if (this.data.isrefresh) {
      this.getalldata();
      this.setData({
        isrefresh: false
      })
    } else {
      this.setData({
        showloading: false,
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var that = this;
    let eTime = new Date();
    let sTime = startTime;
    var t = new Date(eTime - sTime + 16 * 3600 * 1000)
    let info = that.data.info
    console.log(info)
    console.log(t.getSeconds())
    console.log(info.id)
    console.log(info.title)
    that.setData({
      programid: info.id, //栏目id
      programName: info.title, //栏目名称
      stopTime: t.getSeconds(), //页面停留时长
      userIdss: wx.getStorageSync("userId"), //用户id
    })
    console.log("监听页面卸载")
    audioplayUtil.cleartimer2()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.setData({
      page: 1,
      classfilyDataList: []
    })
    this.getdata(id);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var vm = this;
    if (vm.data.buyed) {
      if (vm.data.page < vm.data.totalPages) {
        vm.setData({
          bottomtext: '正在加载中...',
          page: vm.data.page + 1
        })
        vm.getdata(id)
      } else {
        vm.setData({
          bottomtext: '没有更多内容了',
        })
      }
    }

    if (vm.data.collection) {
      if (vm.data.commentPage < vm.data.totalCommentPages) {
        vm.setData({
          bottomtext: '正在加载中...',
          commentPage: vm.data.commentPage + 1
        })
        vm.getCommentData()
      } else {
        vm.setData({
          bottomtext: '没有更多内容了',
        })
      }
    }
  },

  //免费听 
  freelisten: function(e) {
    var that = this;
    var datas = {
      userId: wx.getStorageSync("userId"),
      programId: id,
      shareSource: "0",
    }
    console.log("个人分享。。。。。。")
    console.log(JSON.stringify(datas))
    getApp().request(getApp().globalData.https + "programResource/myProgramShare", //处理获取分享群信息
      "post", datas,
      function(res) {
        if (res.code == "009") {
          wx.showToast({
            title: res.message,
          })
        }
        if (res.code == 0) {
          console.log("调用接口" + res)
          console.log(res)
        }
      },
      function(res) {
        console.log(res)
      }
    )
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    var that = this;
    var id = that.data.info.id
    var imageUrl = getApp().globalData.shareurl
    var title = this.data.info.title
    var userIds = wx.getStorageSync("userId")
    var datas = {
      "userId": userIds,
      "programId": id,
      "shareSource": "0",
    }
    that.singleGroupId(datas); //调取保存用户分享的栏目

    // 判断是不是分享免费听的课程
    if (that.data.info.shareStatus != 1){
      //分享可免费听的课程
      if(that.data.info.listen){
        var info = that.data.info
        //分装提交数据 shareSource 栏目id  shareStatus分享状态
        var datas = {
          "userId": userIds,
          "programId": id,
          "shareSource": "0",
        }
        return {
          title: wx.getStorageSync("userInfo").nickName + '邀您一起听' + info.title,
          path: "/pages/day_day_listen/details/details" + "?userIds=" + userIds + "&id=" + id + "&showhomeicon=fx" + "&url=",
          success(res) { },
          fail(e) {
            console.log("fail")
          },
          //分享完成
          complete() {
            console.log("complete")
          }
        }
      }else{
        var data = {
          programId: id,
          title: title,
          imageUrl: imageUrl,
          path: "/pages/my/my_share/sharing_details/sharing_details"
        }
        return {
          title: wx.getStorageSync("userInfo").nickName + '邀您一起听' + title,
          path: data.path + "?userIds=" + userIds + "&id=" + id + "&showhomeicon=fx",
          imageUrl: data.imageUrl,
          success(res) { },
          fail(e) {
            console.log("fail")
          },
          //分享完成
          complete(res) {
            console.log("complete")
          }
        }
      }
    }else{
      var info = that.data.info
      //分装提交数据 shareSource 栏目id  shareStatus分享状态
      var datas = {
        "userId": userIds,
        "programId": id,
        "shareSource": "0",
      }
      return {
        title: wx.getStorageSync("userInfo").nickName + '邀您一起听' + info.title,
        path: "/pages/day_day_listen/details/details" + "?userIds=" + userIds + "&id=" + id + "&showhomeicon=fx" + "&url=",
        success(res) { },
        fail(e) {
          console.log("fail")
        },
        //分享完成
        complete() {
          console.log("complete")
        }
      }
    }
  },


  /**
   * 个人用户分享保存服务器方法调用
   */
  singleGroupId: function(data) {
    console.log("个人分享。。。。。。")
    getApp().request(getApp().globalData.https + "programResource/myProgramShare", //处理获取分享群信息
      "post", data,
      function(res) {
        if (res.code == "009") {
          wx.showToast({
            title: res.message,
          })
        }
        if (res.code == 0) {
          console.log("调用接口" + res)
          console.log(res)
        }
      },
      function(res) {
        console.log(res)
      }
    )
  },

  shareDetailBindTap: function(e) {
    var id = e.currentTarget.dataset.id;
    console.log(id)
    wx.navigateTo({
      url: "../../my/my_share/sharing_details/sharing_details",
      success: function() {},
      fail: function() {}
    })
  },
  // 回到首页
  gohome: function() {
    wx.switchTab({
      url: '/pages/style/style',
    })
  },
})